package com.emapp.lccode.mode

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.amap.api.maps.AMap
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.Polyline
import com.emapp.lccode.base.BaseApplication
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.bean.DeviceKt
import com.emapp.lccode.bean.DistrictKt
import com.emapp.lccode.bean.OrderKt
import com.emapp.lccode.bean.ProblemTypeKt
import com.emapp.lccode.bean.SelectType
import com.emapp.lccode.bean.UpLatLngKt
import com.emapp.lccode.http.apiService
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.XtomLogger
import com.emapp.lccode.utils.toJsonStr
import com.emapp.lccode.utils.toast
import com.emapp.lccode.view.DistrictDialog
import com.emapp.lccode.view.MapDeviceTypeDialog
import com.hjq.toast.Toaster
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState
import java.util.concurrent.ConcurrentLinkedQueue

class MapViewModel : BaseViewModel() {
    var orders: MutableLiveData<ResultState<OrderKt>> = MutableLiveData()
    var device: MutableLiveData<ResultState<ArrayList<DeviceKt>>> = MutableLiveData()
    var check_id: MutableLiveData<String> = MutableLiveData()
    var types: MutableLiveData<ArrayList<ProblemTypeKt>> = MutableLiveData()
    var typesAll: MutableLiveData<ArrayList<ProblemTypeKt>> = MutableLiveData()
    var districts: MutableLiveData<ArrayList<DistrictKt>> = MutableLiveData()
    var persons: MutableLiveData<ArrayList<ProblemTypeKt>> = MutableLiveData()
    var isFirstLoc = true//第一次定位
    var checkId = ""//巡检id
    var upLatLngs: ArrayList<UpLatLngKt> = arrayListOf()//巡检经纬度数组
    var work_type = "3,6"//设备大分类(水,电)
    var device_type = ""//设备2 3级类 （塘堰(坝)）
    var year = ""
    var city = BaseApplication.instance.getUser()?.city ?: ""
    var district = BaseApplication.instance.getUser()?.district ?: ""
    val typeDialog: MapDeviceTypeDialog by lazy { MapDeviceTypeDialog() }
    val districtDialog: DistrictDialog by lazy { DistrictDialog() }
    var selectType: SelectType = SelectType()
    var selectDistrict: SelectType = SelectType()
    val polylineDataMap: MutableMap<String, DeviceKt> = HashMap()//存放设备（路）与地图polyline的绑定关系，点击路的时候用到
    lateinit var aMap: AMap
   // var markers: ArrayList<Marker> = arrayListOf()//地图显示的数据
    //var lines: ArrayList<Polyline> = arrayListOf()//地图显示的数据
    var lines= ConcurrentLinkedQueue<Polyline>() //地图显示的数据//
    val markers = ConcurrentLinkedQueue<Marker>()
    // 缓存接收到的数据的队列
    lateinit var leftTopLatLng: LatLng
    lateinit var rightBottomLatLng: LatLng
    fun removeMarker(datas: Set<DeviceKt>) {

        val markersToRemove = markers.filter { marker ->
            datas.any { data -> marker.`object` == data }
        }
        log_e("markersToRemove---" + markersToRemove.size)
        markersToRemove.forEach { it.remove() }
        markers.removeAll(markersToRemove)
        val linesToRemove = lines.filter { line ->
            datas.any { data -> polylineDataMap[line.id] == data }
        }
        linesToRemove.forEach { it.remove() }
        lines.removeAll(linesToRemove)
        datas.forEach { data ->
            val key: String? = polylineDataMap.keys.find { polylineDataMap[it] == data }
            if (key != null)
                polylineDataMap.remove(key)
        }
    }

    /**
     * 获取当前巡检
     */
    fun getTrackMapList(work_type: String, mission_id: String, id: String, pager: Int) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.getTrackMapList(
                u.admin_id,
                work_type,
                mission_id,
                id,
                BaseConfig.page_count.toString(),
                pager.toString()
            )
        }, orders, true)
    }

    /**
     * 巡检上报
     */
    fun addMap(
        work_type: String,
        mission_id: String,
        id: String,
        type: String,
        upload_lnglat: String
    ) {
        val u = BaseApplication.instance.getUser() ?: return
        request({
            apiService.mapAdd(
                u.admin_id,
                work_type,
                mission_id,
                id,
                type,
                upload_lnglat
            )
        }, {
            if (type == "2") {
                check_id.postValue("0")
            } else {
                val intValue: Int? = when (it) {
                    is Double -> it.toInt()
                    is Int -> it
                    else -> 1
                }
                check_id.postValue(intValue.toString())
            }
        }, {
            Toaster.show(it.errorMsg)
        })
    }

    /**
     * 分类
     */
//    fun getDeviceType(pid: String) {
//        request({ apiService.getDeviceType(pid) }, types, true)
//    }
    fun getDeviceType(pid: String) {
        request({ apiService.getDeviceType(pid) }, {
            val deTypes: ArrayList<ProblemTypeKt> = arrayListOf()
            viewModelScope.launch {
                withContext(Dispatchers.IO) {
                    val s = it.toJsonStr()
                    MmkvUtil.setType(s)
                }
            }
            typesAll.postValue(it)
            it.forEach { typeKt ->
                if (typeKt.pid == pid) {
                    deTypes.add(typeKt)
                }
            }
            types.postValue(deTypes)

        }, {
            Toaster.show(it.errorMsg)
        }, true)
    }

//    fun getDevice(
//        work_type: String,
//        device_type: String,
//        year: String,
//        city: String,
//        district: String
//    ) {
//        request(
//            { apiService.getDeviceTypeList(work_type, device_type, year, city, district) },
//            device,
//            true
//        )
//    }

    fun getDevice() {
        request(
            {
                apiService.getDeviceTypeList(
                    work_type,
                    device_type,
                    year,
                    city,
                    district,
                    leftTopLatLng.longitude.toString(),
                    leftTopLatLng.latitude.toString(),
                    rightBottomLatLng.longitude.toString(),
                    rightBottomLatLng.latitude.toString()
                )
            },
            device,
            false
        )
    }

    fun getDistrict(pid: String) {
        request({ apiService.getDistrict(pid) }, {
            districts.postValue(it)
        }, {
            Toaster.show(it.errorMsg)
        }, true)
    }

    /**
     * 人员
     */
    fun getPerson(pid: String) {
        request({ apiService.getPerson(pid, BaseApplication.instance.adminId) }, {
            persons.postValue(it)
        }, {
            it.errorMsg.toast()
        }, true)
    }
//         GlobalScope.launch(Dispatchers.Main) {
//             delay(1000L) // 延迟1秒
//             finish() // 关闭当前Activity
//         }


    protected val TAG = this.javaClass.simpleName
    protected open fun log_e(msg: String?) {
        if (BaseConfig.isDebug) XtomLogger.e(TAG, msg)
    }
}